/**
 * 系统配置模块 - 主文件
 * 用于引入拆分后的模块
 */

// 确保在页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否已加载所有必要的脚本
    checkRequiredScripts();
});

// 检查必要的脚本是否已加载
function checkRequiredScripts() {
    const requiredScripts = [
        'settings-core.js',
        'settings-device.js',
        'settings-ventilation.js',
        'settings-account.js'
    ];
    
    let allLoaded = true;
    let missingScripts = [];
    
    requiredScripts.forEach(script => {
        const scriptElement = document.querySelector(`script[src*="${script}"]`);
        if (!scriptElement) {
            allLoaded = false;
            missingScripts.push(script);
            console.warn(`缺少必要的脚本: ${script}`);
        }
    });
    
    if (!allLoaded) {
        console.error(`系统配置模块初始化失败，缺少以下脚本: ${missingScripts.join(', ')}`);
        showError(`系统配置模块初始化失败，缺少必要的脚本文件。请刷新页面或联系管理员。`);
    }
}

// 显示错误信息
function showError(message) {
    if (typeof showToast === 'function') {
        showToast(message, 'error');
    } else {
        alert(message);
    }
}

/**
 * 智能通风配置相关功能
 */

// 全局变量
let activeRow = null;

/**
 * 加载并填充智能通风配置数据
 */
async function loadVentilationConfig() {
    try {
        const configData = await callVentilationApi('getVentilationConfig');
        console.log("获取到通风配置:", configData);

        if (configData && configData.success) {
            updateVentilationTable(configData.data);
        } else {
            showError('加载通风配置失败: ' + (configData ? configData.msg : '无响应'));
        }
    } catch (error) {
        showError('加载通风配置异常: ' + error.message);
    }
}

/**
 * 根据数据更新表格UI
 */
function updateVentilationTable(config) {
    // 定义设备类型和行选择器的映射
    const deviceMapping = {
        'NATURAL_WINDOW': document.querySelector('tr[data-device-type="自然通风窗"]'),
        'AXIAL_FAN': document.querySelector('tr[data-device-type="轴流风机"]'),
        'CIRCULATION_FAN': document.querySelector('tr[data-device-type="环流风机"]')
    };

    for (const deviceKey in config) {
        const row = deviceMapping[deviceKey];
        const data = config[deviceKey];
        if (row && data) {
            row.querySelector('[data-param="temp"] .value-text').textContent = data.targetTemperature;
            row.querySelector('[data-param="humidity"] .value-text').textContent = data.targetHumidity;
            row.querySelector('[data-param="time-range"] .value-text').textContent = `${data.startTime}-${data.endTime}`;
            row.querySelector('[data-param="duration"] .value-text').textContent = data.duration;
        }
    }
}

/**
 * 调用Android或Mock API的通用函数
 */
function callVentilationApi(method, ...args) {
        if (shouldUseMockData()) {
        // 确保IntelligentVentilationMockData存在
        if (window.IntelligentVentilationMockData && typeof window.IntelligentVentilationMockData[method] === 'function') {
            return window.IntelligentVentilationMockData[method](...args);
                } else {
            console.error(`模拟数据方法 ${method} 不存在或不是函数`);
            return Promise.reject(new Error(`模拟数据方法 ${method} 不存在`));
        }
    }
    // 使用通用的Android调用接口
    if (typeof callAndroidMethodAsync === 'function') {
        return callAndroidMethodAsync(method, ...args);
    }
    return Promise.reject(new Error("Android接口尚未实现"));
}

// 显示对话框
function showEditDialog(row) {
    activeRow = row;
    const deviceType = row.dataset.deviceType;
    
    console.log("Editing device:", deviceType);

    const temp = row.querySelector('[data-param="temp"] .value-text').textContent;
    const humidity = row.querySelector('[data-param="humidity"] .value-text').textContent;
    const timeRange = row.querySelector('[data-param="time-range"] .value-text').textContent.split('-');
    const duration = row.querySelector('[data-param="duration"] .value-text').textContent;

    document.getElementById('edit-dialog-title').textContent = '修改 ' + deviceType + ' 参数';
    document.getElementById('edit-temp').value = temp;
    document.getElementById('edit-humidity').value = humidity;
    document.getElementById('edit-start-time').value = timeRange[0] || '';
    document.getElementById('edit-end-time').value = timeRange[1] || '';
    document.getElementById('edit-duration').value = duration;

    // 清除旧的错误提示
    document.getElementById('edit-error-msg').style.display = 'none';
    document.querySelectorAll('.form-group.error').forEach(el => el.classList.remove('error'));

    // 使用新的class来显示
    document.getElementById('edit-ventilation-dialog').style.display = 'flex';
}

// 隐藏对话框
function closeEditDialog() {
    document.getElementById('edit-ventilation-dialog').style.display = 'none';
    activeRow = null;
}

// 保存更改
async function saveChanges() {
    if (!activeRow) return;

    const newStartTimeStr = document.getElementById('edit-start-time').value;
    const newEndTimeStr = document.getElementById('edit-end-time').value;
    const newDurationStr = document.getElementById('edit-duration').value;
    const errorMsgEl = document.getElementById('edit-error-msg');
    const durationInputGroup = document.getElementById('edit-duration').parentElement;

    // 清除旧的错误提示
    errorMsgEl.style.display = 'none';
    errorMsgEl.textContent = '';
    durationInputGroup.classList.remove('error');

    // --- 逻辑验证 ---
    if (!newStartTimeStr || !newEndTimeStr) {
        errorMsgEl.textContent = '请选择应用时间的开始和结束。';
        errorMsgEl.style.display = 'block';
        return;
    }

    const startDate = new Date('1970-01-01T' + newStartTimeStr + ':00');
    const endDate = new Date('1970-01-01T' + newEndTimeStr + ':00');

    if (endDate <= startDate) {
        errorMsgEl.textContent = '结束时间必须晚于开始时间。';
        errorMsgEl.style.display = 'block';
            return;
        }

    const maxDurationInMinutes = (endDate.getTime() - startDate.getTime()) / (1000 * 60);
    const enteredDuration = parseInt(newDurationStr, 10);

    if (isNaN(enteredDuration) || enteredDuration <= 0) {
         errorMsgEl.textContent = '请输入一个有效的、大于0的持续时长。';
         errorMsgEl.style.display = 'block';
         durationInputGroup.classList.add('error');
            return;
        }

    if (enteredDuration > maxDurationInMinutes) {
        errorMsgEl.textContent = `持续时长不能超过 ${maxDurationInMinutes} 分钟。`;
        errorMsgEl.style.display = 'block';
        durationInputGroup.classList.add('error');
                return;
            }
            
    // --- 验证通过，准备数据 ---
    const deviceType = activeRow.dataset.deviceType;
    const deviceKey = getDeviceKeyByName(deviceType); // 将中文名转为常量名
    if(!deviceKey) {
        showError("无法识别的设备类型");
            return;
        }
        
    const configData = {
        [deviceKey]: {
            targetTemperature: parseInt(document.getElementById('edit-temp').value, 10),
            targetHumidity: parseInt(document.getElementById('edit-humidity').value, 10),
            startTime: newStartTimeStr,
            endTime: newEndTimeStr,
            duration: enteredDuration
        }
    };
    
    // --- 调用API保存 ---
    try {
        const result = await callVentilationApi('saveVentilationConfig', configData);
        if (result && result.success) {
            // 保存成功后，更新表格行数据
            updateTableRow(activeRow, configData[deviceKey]);
            closeEditDialog();
            showSuccess("保存成功！");
                } else {
            errorMsgEl.textContent = '保存失败: ' + (result ? result.msg : '无响应');
            errorMsgEl.style.display = 'block';
        }
    } catch(error) {
        errorMsgEl.textContent = '保存异常: ' + error.message;
        errorMsgEl.style.display = 'block';
    }
}

/**
 * 根据保存后的数据更新单行表格
 */
function updateTableRow(row, data) {
    row.querySelector('[data-param="temp"] .value-text').textContent = data.targetTemperature;
    row.querySelector('[data-param="humidity"] .value-text').textContent = data.targetHumidity;
    row.querySelector('[data-param="time-range"] .value-text').textContent = `${data.startTime}-${data.endTime}`;
    row.querySelector('[data-param="duration"] .value-text').textContent = data.duration;
}

/**
 * 将设备中文名转换为mock数据中使用的key
 */
function getDeviceKeyByName(name) {
    const nameMap = {
        '自然通风窗': 'NATURAL_WINDOW',
        '轴流风机': 'AXIAL_FAN',
        '环流风机': 'CIRCULATION_FAN'
    };
    return nameMap[name];
}

// 显示成功消息
function showSuccess(message) {
    if (typeof showToast === 'function') {
        showToast(message, 'success');
                } else {
        alert(message);
    }
}
